package vn.org.cmt.cms.webapp.action;

import java.util.ArrayList;
import java.util.List;

import vn.org.cmt.cms.model.Module;
import vn.org.cmt.cms.service.GenericManager;

import com.opensymphony.xwork2.Preparable;

public class ModuleAction extends BaseAction implements Preparable {
    /**
	 * 
	 */
	private static final long serialVersionUID = 6325204490801865785L;
	/**
	 * 
	 */
    private List modules;
    private Module module;
    private Integer  id;


    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
        	if(!"".equals(getRequest().getParameter("module.id"))){
        		module = moduleManager.getModule((getRequest().getParameter("module.id")));
            }
        }
    }

    public List getModules()
    {
    	return modules;
    }
    
    

    public void setId(Integer  id) {
        this. id =  id;
    }

    public Module getModule()
    {
    	return module;
    }

    public void setModule(Module module) {
        this.module = module;
    }

    public String delete() {
        moduleManager.removeModule(module.getId().toString());
        List<String> args = new ArrayList<String>();
        args.add(module.getName());
        saveMessage(getText("module.deleted", args));

        return SUCCESS;
    }

    /*
    public String edit() {
        if (id != null) {
            module = moduleManager.get(id);
        } else {
            module = new Module();
        }

        return SUCCESS;
    }
    */

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (module.getId() == null);

        moduleManager.save(module);

        String key = (isNew) ? "module.added" : "module.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
    
    /**
     * Default: just returns "success"
     * @return "success"
     */
    public String execute() {
        return SUCCESS;
    }
    
    /**
     * Sends users to "mainMenu" when !from.equals("list"). Sends everyone else to "cancel"
     * @return "mainMenu" or "cancel"
     */
    public String cancel() {
        if (!"list".equals(from)) {
            return "mainMenu";
        }
        return "cancel";
    }
    
    public String list() {
        modules = moduleManager.getModules(new Module());
        return SUCCESS;
    }
}